<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-button type="success" @click="addr">+新增</el-button> </el-col
      ><el-col :span="3">
        <el-input
          placeholder="输入名字"
          v-model="key"
          clearable
          autocomplete="off"
          size="medium"
          @clear="getList"
        ></el-input>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button
          icon="el-icon-search"
          type="info"
          circle
          @click="getList"
        ></el-button>
      </el-col>
    </el-row>
    <el-table :data="product" border style="width: 100%" :default-sort = "{prop: 'updateTime', order: 'descending'}">
      <el-table-column prop="name" label="商品名" width="180">
      </el-table-column>
      <el-table-column sortable prop="price" label="单价(元)" :formatter="rounding">
      </el-table-column>
      <el-table-column prop="image" label="照片">
        <template slot-scope="scope">
          <img :src="scope.row.image" width="80" />
        </template>
      </el-table-column>
      <el-table-column   prop="status" label="状态">
        <template slot-scope="scope">
          <template v-if="scope.row.status === 0"> 充足 </template>
          <template v-else-if="scope.row.status === 1"> 待补货 </template>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column prop="updateTime" label="更新时间"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="warning" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增对话框-->
    <el-dialog title="商品信息" :visible.sync="dialogFormVisible" width="450px">
      <el-form :model="form" ref="form">
        <el-form-item label="条形码" ref="barcode" style="width: 160px">
          <el-input
            v-model="form.barcode"
            autocomplete="off"
            clearable
            @keydown.enter.native="nextFocus(0)"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品名"
          prop="name"
          size="small"
          style="width: 160px"
        >
          <el-input
            v-model="form.name"
            autocomplete="off"
            @keydown.enter.native="nextFocus(1)"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价" size="small" style="width: 160px">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <div>
          <span>上传图片</span>
          <el-upload
            class="avatar-uploader"
            action="http://localhost:11143/common/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            clearable
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <span>分组选择</span>
        <el-cascader
          v-model="form.categoryId"
          style="width: 160px"
          size="medium"
          :options="tree"
          @change="categoryChange"
          :props="{
            checkStrictly: true,
            label: 'categoryName',
            value: 'categoryId',
            children: 'sonList',
            emitPath: false,
          }"
          clearable
          filterable
        ></el-cascader>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json
import http from "../utils/request";

//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      saveOrUpdate: "",
      categoryId:null,
      imageUrl: "",
      product: [],
      tree: [],
      page: 1,
      limit: 10,
      key: "",
      dialogFormVisible: false,
      form: {
        productId: "",
        name: "",
        barcode: "",
        categoryId: "",
        image: "",
        price: "",
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleDelete(product) {
      http.delete(`/product/delete/${product.productId}`).then(({ data }) => {
        if (data.code == 1) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        }
      });
    },
    handleEdit(product) {
      console.info("查看", product);
      http.get(`/product/get/${product.productId}`).then(({ data }) => {
        if (data.code == 1) {
          this.$message({
            type: "success",
            message: "获取成功!",
          });
          this.dialogFormVisible = true;
          this.saveOrUpdate = 1;
          this.form.productId = data.data.productId;
          this.form.name = data.data.name;
          this.form.barcode = data.data.barcode;
          this.form.categoryId = data.data.categoryId;
          this.form.image = data.data.image;
          this.form.price = data.data.price;
          console.log("输入了条形码", this.form);
        }
      });
    },
    rounding(row, column) {
      return parseFloat(row[column.property]).toFixed(2);
    },

    nextFocus(index) {
      console.log("输入了条形码");
      if (index < 5) {
        this.$refs["form"].$el[index + 1].focus();
      } else {
        this.submit();
      }
    },
    deleteById() {},
    submit() {
      if (this.saveOrUpdate == 0) {
        this.form.image = this.imageUrl;
        http.post("/product/save", this.form).then(({ data }) => {
          console.info("返回数据", data);
          if (data.code == 1) {
            //这里加一个提示框
            this.$message({
              type: "success",
              message: "保存成功!",
            });
            console.info("保存成功");
            this.getList();
            this.dialogFormVisible = false;
            this.form = {
              productId: "",
              name: "",
              barcode: "",
              categoryId: "",
              image: "",
              price: "",
            };
          }
        });
      } else if (this.saveOrUpdate == 1) {
        http.put(`/product/update`, this.form).then(({ data }) => {
          console.info("返回数据", data);
          if (data.code == 1) {
            //这里加一个提示框
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            console.info("编辑成功");
            this.getList();
            this.dialogFormVisible = false;
            this.form = {
              productId: "",
              name: "",
              barcode: "",
              categoryId: "",
              image: "",
              price: "",
            };
          }
        });
      }
    },
    categoryChange() {
      // this.form.categoryId = this.tree.categoryId;
      console.log("选中了分组", this.form.categoryId);
    },
    addr() {
      this.form = {
        productId: "",
        name: "",
        barcode: "",
        categoryId: "",
        image: "",
        price: "",
      };
      console.log("点击新增按钮啦");
      this.dialogFormVisible = true;
      this.saveOrUpdate = 0;
    },
    treeitem(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].sonList.length < 1) {
          data[i].sonList = undefined;
        } else {
          this.treeitem(data[i].sonList);
        }
      }
      return data;
    },
    getCategory() {
      http.get("/category/tree", "").then(({ data }) => {
        console.info("接收到分组数据", data.data);
        this.tree = this.treeitem(data.data);
      });
    },

    getList() {
      http
        .get(
          `/product/list?page=${this.page}&limit=${this.limit}&key=${this.key}&categoryId=${this.categoryId}`
        )
        .then(({ data }) => {
          console.info("接收到传入数据", data.data);
          this.product = data.data.records;
          console.info("接收到解析数据", this.product);
        });
    },
    handleAvatarSuccess(res, file) {
      console.log("返回的链接是", res.data);
      this.imageUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getList();
    this.getCategory();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
//@import url(); 引入公共 css 类
</style>
